package com.zyh.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zyh.entity.Attr;
import com.zyh.entity.AttrGroup;
import com.zyh.entity.AttrGroupDto;
import com.zyh.entity.ResultEntity;
import com.zyh.service.IAttrGroupService;
import com.zyh.service.IAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 属性分组 前端控制器
 * </p>
 *
 * @author zhang
 * @since 2022-05-11
 */
@RestController
@RequestMapping("/group")
public class AttrGroupController {
    @Autowired
    private IAttrGroupService attrGroupService;
    @Autowired
    private IAttrService attrService;

    //根据商品类别编号查询该类别下的属性分组信息
    @GetMapping("/selectGroupsByCategoryId/{categoryId}")
    public ResultEntity<List<AttrGroup>> selectGroupsByCategoryId(@PathVariable("categoryId") Integer categoryId){
        List<AttrGroup> list = attrGroupService.list(new QueryWrapper<AttrGroup>().eq("category_id",categoryId));
        return ResultEntity.ok(list);
    }

    //添加分组信息
    @PostMapping("/add")
    public ResultEntity add(@RequestBody AttrGroup attrGroup){
        //boolean save = attrGroupService.save(attrGroup);
        return attrGroupService.save(attrGroup)==true ? ResultEntity.ok() : ResultEntity.error("添加失败！");
    }

    //根据id查询分组信息
    @GetMapping("/selectOne/{groupId}")
    public ResultEntity<AttrGroup> selectOne(@PathVariable("groupId") Integer groupId){
        return ResultEntity.ok(attrGroupService.getById(groupId));
    }

    //修改分组信息
    @PutMapping("/update")
    public ResultEntity update(@RequestBody AttrGroup attrGroup){
        return ResultEntity.ok(attrGroupService.updateById(attrGroup));
    }

    //给属性分组关联属性
    @PostMapping("/attrToGroup")
    public ResultEntity attrToGroup(@RequestBody AttrGroupDto attrGroupDto){
        Integer groupId = attrGroupDto.getGroupId();
        Integer[] attrIds = attrGroupDto.getAttrIds();
        for (int i = 0; i < attrIds.length; i++) {
            UpdateWrapper<Attr> wrapper = new UpdateWrapper<>();
            wrapper.eq("attr_id",attrIds[i]).set("attr_group_id",groupId);
            attrService.update(null,wrapper);
        }
        return ResultEntity.ok();
    }
}

